<template>
    <tableLayout :columns="columns" :operationShow="true" :get="getData" :selectItem="selectItem" :rules="rules"
        ref="layout" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <template #button>
            <a-button type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
            <a-button style="margin-left: 20px" @click="edit" :disabled="selectedRowKeys.length !== 1">修改</a-button>
            <a-button type="primary" style="margin-left: 20px" @click="del" :disabled="selectedRowKeys.length !== 1"
                danger>删除</a-button>
        </template>

        <template #operationMore="item">
            <a @click="edit(null, item.value.record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="del(null, item.value.record.Id)">删除</a>
        </template>

        <template v-slot:custom="data">
            <a-input v-model:value="data.formData[data.key]" />
        </template>
    </tableLayout>



    <a-modal :title="formState.Id ? '编辑表单' : '新增表单'" v-model:visible="modal_visible" :confirm-loading="confirmLoading"
        @ok="modal_handleOk" width="1200px">
        <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"
            layout="inline" class="comform">
            <a-form-item label="名称" style="width: calc(50% - 20px);" class="form__item" name="Name">
                <a-input v-model:value="formState.Name" placeholder="名称" />
            </a-form-item>
            <a-form-item label="表单编码" style="width: calc(50% - 20px);" class="form__item" name="Code">
                <a-input v-model:value="formState.Code" :readonly="true" placeholder="表单编码">
                    <template #suffix>
                        <a-tooltip title="复制表单编码">
                            <CopyTwoTone style="color: rgba(0, 0, 0, 0.45)" @click="onCopyOnlineFormCode" />
                        </a-tooltip>
                    </template>
                </a-input>
            </a-form-item>
            <!-- 添加数据来源下拉框 -->
            <a-form-item label="数据来源" style="width: calc(50% - 20px);" class="form__item" name="DataForm">
                <a-select v-model:value="formState.DataForm" placeholder="请选择数据来源" @change="onDataFormChange">
                    <a-select-option :value="1">API</a-select-option>
                    <a-select-option :value="2">数据表</a-select-option>
                    <a-select-option :value="3">静态数据</a-select-option>
                    <a-select-option :value="4">文件</a-select-option>
                </a-select>
            </a-form-item>
            <!-- <a-form-item label="API地址" style="width: calc(50% - 20px);" class="form__item" name="ApiUrl" v-show="formState.DataForm==DataForm.API">
                <a-input v-model:value="formState.ApiUrl" placeholder="请输入API地址" />
            </a-form-item> -->
            <a-form-item label="数据表" style="width: calc(50% - 20px);" class="form__item" name="TableId"
                v-show="formState.DataForm == DataForm.DataBase">
                <a-select v-model:value="formState.TableId" @change="onTableChange">

                    <a-select-option v-for="item in tableOptions" :key="item.Id" :value="item.Id">
                        {{ item.TableComments }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="表描述" style="width: calc(50% - 20px);" class="form__item" name="TableComments"
                v-show="formState.DataForm == DataForm.DataBase">
                <a-input v-model:value="formState.TableComments" disabled placeholder="请输入表描述" />
            </a-form-item>
            <a-form-item label="表编码" style="width: calc(50% - 20px);" class="form__item" name="TableCode"
                v-show="formState.DataForm == DataForm.DataBase">
                <a-input v-model:value="formState.TableCode" placeholder="请输入表编码" disabled />
            </a-form-item>
            <a-form-item label="是否分页" style="width: calc(50% - 20px);" class="form__item" name="IsPage">
                <a-checkbox v-model:checked="formState.IsPage" />
            </a-form-item>
            <a-form-item label="显示复选框" style="width: calc(50% - 20px);" class="form__item" name="IsShowCheckBox">
                <a-checkbox v-model:checked="formState.IsShowCheckBox" />
            </a-form-item>
            <a-form-item label="是否单选" style="width: calc(50% - 20px);" class="form__item" name="IsSingleSelected">
                <a-checkbox v-model:checked="formState.IsSingleSelected" />
            </a-form-item>
            <a-form-item label="是否有效" style="width: calc(50% - 20px);" class="form__item" name="IsValid">
                <a-checkbox v-model:checked="formState.IsValid" />
            </a-form-item>

            <a-form-item label="备注" style="width: calc(100% - 20px);" class="form__item" name="Description"
                :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-textarea v-model:value="formState.Description" placeholder="备注" :rows="4" />
            </a-form-item>

        </a-form>
        <!-- API配置面板，只在数据来源为API时显示 -->
        <div v-show="formState.DataForm === 1" style="margin-top: 16px;">
            <hr style="border-style: dashed;" />
            <div style="margin-bottom: 16px;">
                <a-button type="primary" @click="addApiConfig"> <template #icon>
                        <PlusOutlined />
                    </template>新增API配置</a-button>
            </div>
            <!-- 修改为Tabs组件显示API配置 -->
            <a-tabs v-model:activeKey="activeApiTabKey" type="editable-card" @edit="handleApiTabEdit">
                <a-tab-pane 
                    v-for="(apiConfig, index) in apiConfigs" 
                    :key="apiConfig.id" 
                    :tab="getApiConfigTabTitle(apiConfig)"
                >
                    <a-form :model="apiConfig" layout="inline" :labelCol="labelCol" :wrapperCol="wrapperCol" class="comform">
                        <a-form-item label="API类型" style="width: calc(50% - 20px);" class="form__item">
                            <a-select v-model:value="apiConfig.type" placeholder="请选择API类型" @change="onApiTypeChange(index, $event)">
                                <a-select-option :value="'add'">新增</a-select-option>
                                <a-select-option :value="'saveOrUpdate'">新增/修改</a-select-option>
                                <a-select-option :value="'update'">修改</a-select-option>
                                <a-select-option :value="'delete'">删除</a-select-option>
                                <a-select-option :value="'get'">查询</a-select-option>
                                <a-select-option :value="'custom'">自定义</a-select-option>
                            </a-select>
                        </a-form-item>

                        <a-form-item label="请求方法" style="width: calc(50% - 20px);" class="form__item">
                            <a-select v-model:value="apiConfig.method" placeholder="请选择请求方法">
                                <a-select-option :value="'GET'">GET</a-select-option>
                                <a-select-option :value="'POST'">POST</a-select-option>
                                <a-select-option :value="'PUT'">PUT</a-select-option>
                                <a-select-option :value="'DELETE'">DELETE</a-select-option>
                            </a-select>
                        </a-form-item>

                        <a-form-item label="请求URL" style="width: calc(100% - 20px);" class="form__item" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                            <a-input v-model:value="apiConfig.url" placeholder="请输入请求URL" />
                        </a-form-item>

                        <!-- 当API类型为自定义时，显示脚本编辑窗口 -->
                        <a-form-item v-if="apiConfig.type === 'custom'" label="自定义脚本" style="width: calc(100% - 20px);"
                            class="form__item" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                            <a-textarea v-model:value="apiConfig.script" placeholder="请输入自定义脚本" :rows="8" />
                        </a-form-item>
                    </a-form>
                </a-tab-pane>
            </a-tabs>
        </div>
        <hr style="border-style: dashed;" />


        <!-- 添加Tabs组件 -->
        <a-tabs activeKey="field" style="margin-top: 16px;">
            <a-tab-pane key="field" tab="表格数据">
                <a-button type="primary" style="margin-top: 10px;margin-left:10px" size="small" @click="addColumn">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    创建字段</a-button>
                <a-table :columns="table_columns" size="small" rowKey="Key" :data-source="onlineFieldDataSource"
                    :pagination="false" :scroll="{ y: 320 }" style="margin-top: 10px;" bordered>
                    <template
                        v-for="col in ['FieldCnName', 'FieldEnName', 'FiledType', 'IsOrder', 'IsValid', 'IsTableShow', 'IsSearch', 'IsFormShow', 'IsRequired']"
                        #[col]="{ text, record }" :key="col">
                        <div>
                            <a-select v-model:value="record[col]" v-if="col == 'FiledType'" style="width: 90px;">
                                <a-select-option :value="1">字符串</a-select-option>
                                <a-select-option :value="2">整数</a-select-option>
                                <a-select-option :value="3">小数</a-select-option>
                                <a-select-option :value="4">日期时间</a-select-option>
                                <a-select-option :value="5">布尔类型</a-select-option>
                                <a-select-option :value="6">二进制</a-select-option>
                            </a-select>

                            <a-checkbox v-model:checked="record[col]"
                                v-else-if="['IsValid', 'IsTableShow', 'IsSearch', 'IsFormShow', 'IsOrder', 'IsRequired'].includes(col)"></a-checkbox>

                            <a-input v-else v-model:value="record[col]" style="margin: -5px 0" />

                        </div>
                    </template>
                    <template #operation="{ record }">
                        <div class="editable-row-operations">

                            <span>
                                <a @click="moveUp(record)">上移</a>
                            </span>
                            <span>
                                <a @click="moveDown(record)">下移</a>
                            </span>
                            <span>
                                <Confirm title="删除不能恢复，确认要删除?" @confirm="onDeleteColumn(record)">
                                    <template #button>
                                        <a>删除</a>
                                    </template>
                                </Confirm>
                            </span>
                        </div>
                    </template>
                </a-table>
            </a-tab-pane>
        </a-tabs>

    </a-modal>

</template>

<script lang="ts" setup>
import { notification, message } from 'ant-design-vue';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { getData, getDataSourceTables, getOnlineFieldsByOnlineInfoId, saveOrUpdateDataSource, getTableColumnData } from '@/api/online/online';

import { ref, UnwrapRef, reactive, nextTick, h } from 'vue';
import { CopyTwoTone, PlusOutlined } from '@ant-design/icons-vue';
import { OnlineInput, DataForm } from '@/types/api/online/online';
import { CustomIdPrefix } from '@/components/id/idGenerater';
import Confirm from '@/components/controls/confirm.vue';



const layout = ref();
const modal_visible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const formRef = ref()
const tableOptions = ref([]);

// 定义API配置项接口
interface ApiConfig {
    id: string;
    type: string;
    method: string;
    url: string;
    script: string;
}

//表单对象
const formState: UnwrapRef<OnlineInput> = reactive({
    Id: '',
    Name: '',
    Code: '',
    TableComments: '',
    TableId: '',
    TableCode: '',
    DataForm: null,
    ApiConfigs: '',
    IsValid: true,
    IsPage: true,
    IsSingleSelected: true,
    IsShowCheckBox: true,
    Description: '',
    OnlineFieldInputs: [],
});

// API配置数组
const apiConfigs = ref<ApiConfig[]>([]);
// 当前激活的API配置标签页Key
const activeApiTabKey = ref<string>('');

// 获取API配置的标签标题
const getApiConfigTabTitle = (apiConfig: ApiConfig): string => {
    const typeMap: Record<string, string> = {
        'add': '新增',
        'update': '修改',
        'delete': '删除',
        'custom': '自定义',
        'saveOrUpdate': '新增/修改',
        'get': '查询'
    };
    return typeMap[apiConfig.type] || '未知类型';
};

// 添加一个API配置
const addApiConfig = () => {
    // 默认添加自定义类型，因为其他类型可能已经存在
    const newConfig: ApiConfig = {
        id: CustomIdPrefix('ApiConfig').toString(),
        type: 'custom',
        method: 'GET',
        url: '',
        script: ''
    };
    apiConfigs.value.push(newConfig);
    // 设置新添加的标签为激活状态
    nextTick(() => {
        activeApiTabKey.value = newConfig.id;
    });
};

// 处理标签页编辑事件
const handleApiTabEdit = (targetKey: string, action: 'add' | 'remove') => {
    if (action === 'remove') {
        removeApiConfig(targetKey);
    }else{
        addApiConfig();
    }
};

// 删除API配置
const removeApiConfig = (id: string) => {
    const index = apiConfigs.value.findIndex(config => config.id === id);
    if (index !== -1) {
        apiConfigs.value.splice(index, 1);
        // 如果删除的是当前激活的标签，激活第一个可用标签
        if (activeApiTabKey.value === id && apiConfigs.value.length > 0) {
            activeApiTabKey.value = apiConfigs.value[0].id;
        }
    }
};

// 当API类型改变时检查唯一性
const onApiTypeChange = (index: number, newType: string) => {
    // 如果不是自定义类型，检查是否已经存在该类型的配置
    if (newType !== 'custom') {
        const existingIndex = apiConfigs.value.findIndex((config, idx) => 
            idx !== index && config.type === newType
        );
        
        if (existingIndex !== -1) {
            message.warning(`"${getApiConfigTabTitle({ type: newType } as ApiConfig)}"类型的API配置只能有一个，已自动切换为自定义类型`);
            // 自动复位到自定义类型
            nextTick(() => {
                apiConfigs.value[index].type = 'custom';
            });
            return;
        }
    }
};

//列表
const columns = [
    { title: '名称', dataIndex: 'Name' },
    { title: '编码', dataIndex: 'Code' },

    {
        title: '是否有效', dataIndex: 'IsValid', customRender: function ({ text }): VNode {
            return h('div', {
                style: {
                    color: 'red'
                }
            }, text == 1 ? '有效' : '无效');
        }
    },
    {
        title: '是否分页', dataIndex: 'IsPage', customRender: function ({ text }): VNode {
            return h('div', {
                style: {
                    color: 'red'
                }
            }, text == 1 ? '是' : '否');
        }
    },
    {
        title: '单选', dataIndex: 'IsSingleSelected', customRender: function ({ text }): VNode {

            return h('div', {
                style: {
                    color: 'red'
                }
            }, text == 1 ? '是' : '否');
        }
    },
    {
        title: '显示复选框', dataIndex: 'IsShowCheckBox', customRender: function ({ text }): VNode {

            return h('div', {
                style: {
                    color: 'red'
                }
            }, text == 1 ? '是' : '否');
        }
    },
    { title: '创建时间', dataIndex: 'CreateTime' }
]

const table_columns = [
    { title: '序号', dataIndex: 'SortNum', width: 60 },
    { title: '字段名称', dataIndex: 'FieldCnName', slots: { customRender: 'FieldCnName' } },
    { title: '字段', dataIndex: 'FieldEnName', slots: { customRender: 'FieldEnName' } },
    { title: '类型', dataIndex: 'FiledType', width: 100, slots: { customRender: 'FiledType' } },
    { title: '有效', dataIndex: 'IsValid', width: 100, slots: { customRender: 'IsValid' } },
    { title: '排序', dataIndex: 'IsOrder', width: 60, slots: { customRender: 'IsOrder' } },
    { title: '显示', dataIndex: 'IsTableShow', width: 60, slots: { customRender: 'IsTableShow' } },
    { title: '查询', dataIndex: 'IsSearch', width: 60, slots: { customRender: 'IsSearch' } },
    { title: '表单显示', dataIndex: 'IsFormShow', width: 80, slots: { customRender: 'IsFormShow' } },
    { title: '必填', dataIndex: 'IsRequired', width: 60, slots: { customRender: 'IsRequired' } },
    { title: '操作', dataIndex: 'operation', width: 180, slots: { customRender: 'operation' } }

]

const onlineFieldDataSource = ref([]);

// 筛选
const selectItem = ref([
    { title: '名称', key: 'Name', type: 'input', itemWidth: '290px' },
    { title: '编码', key: 'Code', type: 'input', itemWidth: '290px' },
])

// 规则
const rules = {
    Name: [{ required: true, message: '请输入名称', trigger: 'change' }],
    Code: [{ required: true, message: '请输入编码', trigger: 'change' }],
    DataForm: [{ required: true, message: '请选择数据来源' }]
}

//新增
const add = () => {
    modal_visible.value = true;
    let code = CustomIdPrefix("OnlineForm");
    Object.keys(formState).forEach(key => {
        if (key === 'Code') {
            formState[key] = code;
        } else {
            formState[key] = ''; // 清空其他字段
        }
    });
    onlineFieldDataSource.value = [];
    onlineFieldDataSource.value.push({ FieldCnName: '', FieldEnName: '', FiledType: 1, IsOrder: false, SortNum: 1, IsValid: true, IsTableShow: true, IsSearch: false, IsFormShow: true });
}

const edit = (event: any, item: any) => {
    let selectItem = item;
    if (!selectItem) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectItem = selectedRows.value[0];
    }
    modal_visible.value = true;
    Object.assign(formState, selectItem);
    apiConfigs.value = selectItem.ApiConfigs ? JSON.parse(selectItem.ApiConfigs) : [];
    // 设置第一个API配置为激活状态
    if (apiConfigs.value.length > 0) {
        activeApiTabKey.value = apiConfigs.value[0].id;
    }
    
    getOnlineFieldsByOnlineInfoId({ onlineInfoId: selectItem.Id }).then(e => {
        var data = e.data.Data || [];
        //给data设置Key
        data.forEach((item: any, index: number) => {
            let key = CustomIdPrefix('TableColumnKey');
            item.Key = key;
        });
        //data排序
        data.sort((a: any, b: any) => {
            return a.SortNum - b.SortNum;
        });
        onlineFieldDataSource.value = data;
    }).catch(err => {
        console.log(err);
        message.error(err.message || "获取字段数据失败!")
    })
}
const loadDataSourceTables = () => {
    getDataSourceTables().then(e => {
        tableOptions.value = e.data.Data;
    }).catch(err => {
        console.log(err)
        message.error(err.message || "获取失败!")
    });
}

const onDataFormChange = (event: any) => {
    if (formState.DataForm == DataForm.DataBase) {
        loadDataSourceTables();
    } else {
        formState.TableId = '';
        formState.TableComments = '';
        formState.TableCode = '';
    }
}

//删除一条记录
const del = (event: any, id: any) => {
    let selectId = id;
    if (!selectId) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectId = selectedRows.value[0].Id;
    }

    deleteDataSource({ Id: selectId }).then(() => {
        message.success("删除成功!");
        layout.value.getData();
    }).catch(err => {
        message.error(err.message || "删除失败!")
        confirmLoading.value = false;
    })
}

//复制表单编码
const onCopyOnlineFormCode = async (event: any) => {
    try {
        await navigator.clipboard.writeText(formState.Code);
        message.success('复制成功！');
    } catch (err) {
        console.error('复制失败', err);
        message.error('复制失败，请手动复制');
    }
}

//选择数据表
const onTableChange = async (event: any) => {
    let tableOption = tableOptions.value.find(e => e.Id == event);
    formState.TableComments = tableOption.TableComments;
    formState.TableCode = tableOption.TableCode;
    getTableColumnData({ dataSourceTableId: event }).then(e => {
        var data = e.data.Data || [];
        //给data设置Key
        data.forEach((item: any, index: number) => {
            let key = CustomIdPrefix('OnlineFormColumn');
            item.Key = key;
        });
        //data排序
        data.sort((a: any, b: any) => {
            return a.SortNum - b.SortNum;
        });
        onlineFieldDataSource.value = data;
    }).catch(err => {
        console.log(err);
        message.error(err.message || "获取字段数据失败!")
    })
}


// 多选
const selectedRowKeys = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const singleSelection = ref<any[]>([]);
const onSelectChange = (keys: [], rows: any) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
    singleSelection.value = rows[0];
}

const modal_handleOk = () => {
    formRef.value.validate().then(() => {
        confirmLoading.value = true;
        formState.OnlineFieldInputs = onlineFieldDataSource.value;
        formState.ApiConfigs = JSON.stringify(apiConfigs.value);
        saveOrUpdateDataSource(formState).then(e => {
            message.success("操作成功！");
            confirmLoading.value = false;
            modal_visible.value = false;
            layout.value.getData();
            selectedRowKeys.value = [];
        }).catch(err => {
            message.error(err.message || "操作失败!")
            confirmLoading.value = false;
        })
    }).catch(() => {
        confirmLoading.value = false;
        message.error('请检查必填项是否全部填写!');
    })
}

const addColumn = () => {
    let key = CustomIdPrefix('TableColumnKey');
    let sortNum = onlineFieldDataSource.value.length + 1;
    onlineFieldDataSource.value.push({ FieldCnName: '', FieldEnName: '', FiledType: 1, IsOrder: false, SortNum: sortNum, IsValid: true, IsTableShow: true, IsSerch: false, IsFormShow: true });
}
//删除字段
const onDeleteColumn = (record: any) => {
    let index = onlineFieldDataSource.value.findIndex(e => e == record);
    if (index >= 0) {
        onlineFieldDataSource.value.splice(index, 1);
    }
    //后面的重新排序
    for (let i = index; i < onlineFieldDataSource.value.length; i++) {
        onlineFieldDataSource.value[i].SortNum = onlineFieldDataSource.value[i].SortNum - 1;
    }
}

//上移
const moveUp = (record: any) => {
    debugger
    let index = onlineFieldDataSource.value.findIndex(e => e == record);
    if (index > 0) {
        let temp = onlineFieldDataSource.value[index];
        let tempSortNum = temp.SortNum;
        onlineFieldDataSource.value[index] = onlineFieldDataSource.value[index - 1];
        onlineFieldDataSource.value[index - 1] = temp;
        onlineFieldDataSource.value[index - 1].SortNum = onlineFieldDataSource.value[index].SortNum;
        onlineFieldDataSource.value[index].SortNum = tempSortNum;
    }
}

//下移
const moveDown = (record: any) => {
    let index = onlineFieldDataSource.value.findIndex(e => e == record);
    if (index < onlineFieldDataSource.value.length - 1) {
        let temp = onlineFieldDataSource.value[index];
        let tempSortNum = temp.SortNum;
        onlineFieldDataSource.value[index] = onlineFieldDataSource.value[index + 1];
        onlineFieldDataSource.value[index + 1] = temp;
        onlineFieldDataSource.value[index + 1].SortNum = onlineFieldDataSource.value[index].SortNum;
        onlineFieldDataSource.value[index].SortNum = tempSortNum;
    }
}


const labelCol = { span: 6 };
const wrapperCol = { span: 18 };
</script>

<style lang="scss" scoped>
.editable-row-operations {
    a {
        margin-right: 8px;
    }

    .disabled {
        a {
            color: #ccc;
            cursor: not-allowed;
        }
    }
}

.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;

    }


    .ant-modal-body {
        flex: 1;
    }
}

.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1 !important;
            flex-shrink: 0;
        }
    }
}
</style>
<style lang="scss">
.editable-row-operations a {
    margin-right: 8px;
}

.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;

    }



    .ant-modal-body {
        flex: 1;
    }
}

.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1;
            flex-shrink: 0;
        }
    }
}
</style>